<template>
	<view class="info">
		<view class="info-wrap">
			<view class="content">
				<textarea placeholder="现在在想些什么？" class="txt" maxlength="1000" :auto-height="true"
					v-model="momentInfo.content"></textarea>
			</view>
			
			<!-- 图片上传区域 -->
			<view class="post-img-wrap" v-if="momentInfo.mediaType == 1 && momentMediaList.length != 0">
				<u-upload ref="uUpload" name="file" :max-count="9" :size-type="['original']" :custom-btn="true" :fileList="momentMediaList"
				 :header="header" :action="uploadUrl" @on-success="uploadMediaSuccess"  @on-remove="removeImage" :width="212" :height="212"
					>
					<template v-slot:addBtn>
						<view class="slot-btn">
							<u-icon name="plus" size="50" color="#797979"></u-icon>
							<view class="slot-txt">
								上传照片
							</view>
						</view>
					</template>
				</u-upload>
			</view>
			
			<!-- 视频上传区域 -->
			<view class="video-wrap" v-if="momentInfo.mediaType == 2 && videoUrl">
				<video id="video" :src="videoUrl" controls class="upload-video" :poster="videoCover"></video>
				<!-- <image v-if="showPlay" @click="playVideo" src="/static/image/video.png"></image> -->
				<view class="icon" @click="removeVideo">
					<u-icon name="close" size="30" color="#797979"></u-icon>
				</view>
			</view>
			
			<view class="footer">
				<view class="tool2">
					<image @click="selectImage" src="/static/image/album.png"></image>
					<image @click="selectVideo" :class="momentInfo.mediaType != 1?'':'disabled'" src="/static/image/video.png" style="margin-left: 20rpx;"></image>
					<view class="submit"  @click="submit" :class="noneContent()?'grey':'blue'">发布</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import request from '@/utils/request.js';
import config from '@/utils/config.js';

const header = ({token: uni.getStorageSync('token')})
const uploadUrl = config.uploadUrl
const momentMediaList = ref([])
const videoUrl = ref('')
const videoCover = ref('') // 新增：视频封面
const momentInfo = ref({
	content:null,
	mediaType:null, // 1:图片 2:视频
	mediaList:[],
})
const videoContext = ref(null)
const showPlay = ref(true)

onLoad((options) => {
})

// 新增：获取视频封面
const getVideoCover = (videoPath) => {
	debugger
  return new Promise((resolve, reject) => {
    uni.getVideoInfo({
      src: videoPath,
      success: (res) => {
		  debugger
        if (res.thumbTempFilePath) {
          resolve(res.thumbTempFilePath);
        } else {
          reject(new Error('无法获取视频封面'));
        }
      },
      fail: reject
    });
  });
}

const selectImage = () => {
	if(momentInfo.value.mediaType == 2){
		uni.showToast({
			title: '只能选择图片或视频中的一种',
			icon: 'none'
		})
		return
	}
	uni.chooseImage({
		count: 9,
		sizeType: ['original', 'compressed'], 
		sourceType: ['album','camera'], 
		success: async function (res) {
			momentInfo.value.mediaType = 1
			let fileList = res.tempFiles
			let showList = []
			momentMediaList.value = []
			let count = 0
			fileList.forEach(file => {
				uploadFile(file.path).then((url) =>{
					count ++
					showList.push({url:url})
				})
			})
			let timer =  setInterval(() => {
				if(count == fileList.length){
					clearInterval(timer);
					momentMediaList.value = showList
				}
			},500);
		}
	});
}

const selectVideo = () => {
  if (momentInfo.value.mediaType == 1) {
    uni.showToast({
      title: '只能选择图片或视频中的一种',
      icon: 'none'
    })
    return
  }

  uni.chooseVideo({
    sourceType: ['album', 'camera'],
    maxDuration: 60,
    compressed: true,
    success: async function (res) {
      momentInfo.value.mediaType = 2
      videoUrl.value = ''
      videoCover.value = ''
      
      uni.showLoading({
        title: '视频处理中',
        mask: true
      })

      try {
        let coverUrl = ''
        let videoInfo = {}
        
        // 尝试获取视频信息
        try {
          videoInfo = await new Promise((resolve, reject) => {
            uni.getVideoInfo({
              src: res.tempFilePath,
              success: resolve,
              fail: reject
            })
          })
          
          // H5环境下可能没有thumbTempFilePath
          if (videoInfo.thumbTempFilePath) {
            coverUrl = await uploadFile(videoInfo.thumbTempFilePath)
          }
        } catch (e) {
          console.warn('获取视频信息失败:', e)
        }

        // 如果封面仍未获取到，使用canvas截取
        if (!coverUrl) {
          try {
            const coverPath = await captureVideoFrame(res.tempFilePath, videoInfo)
            if (coverPath) {
              coverUrl = await uploadFile(coverPath)
            }
          } catch (e) {
            console.warn('Canvas截取封面失败:', e)
          }
        }

        // 上传视频
        const url = await uploadFile(res.tempFilePath)
        videoUrl.value = url
        videoCover.value = coverUrl || '' // 保存封面URL，即使为空
        showPlay.value = true

        nextTick(() => {
          videoContext.value = uni.createVideoContext('video', this)
        })

        // 更新媒体列表
        momentInfo.value.mediaList = [{
          url: url,
          cover: coverUrl || '',
          type: 'video',
          width: videoInfo.width,
          height: videoInfo.height,
          duration: videoInfo.duration
        }]

      } catch (e) {
        console.error('视频处理失败', e)
        uni.showToast({
          title: '视频处理失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  })
}

// 专门用于H5环境的封面截取方法
const captureVideoFrame = (videoPath, videoInfo = {}) => {
  return new Promise((resolve, reject) => {
    // 如果是H5环境
    if (process.env.VUE_APP_PLATFORM === 'h5') {
      const video = document.createElement('video')
      video.crossOrigin = 'anonymous'
      video.src = videoPath
      
      video.onloadedmetadata = () => {
        video.currentTime = Math.min(1, video.duration / 2) // 取中间帧避免黑屏
      }

      video.onseeked = () => {
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth || videoInfo.width || 540
        canvas.height = video.videoHeight || videoInfo.height || 960
        
        const ctx = canvas.getContext('2d')
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        
        canvas.toBlob(blob => {
          const url = URL.createObjectURL(blob)
          resolve(url)
        }, 'image/jpeg', 0.8)
      }

      video.onerror = reject
    } else {
      // 非H5环境使用uni-app的canvas
      const ctx = uni.createCanvasContext('videoCoverCanvas', this)
      ctx.drawImage(videoPath, 0, 0, videoInfo.width || 540, videoInfo.height || 960)
      ctx.draw(false, () => {
        uni.canvasToTempFilePath({
          canvasId: 'videoCoverCanvas',
          success: resolve,
          fail: reject
        }, this)
      })
    }
  })
}

const uploadFile = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: uploadUrl, //文件上传接口
			filePath: filePath,
			header: header,
			name:'file',
			fail(res) {
				uni.hideLoading()
				reject(res)
			},
			success: (res) => {
				uni.hideLoading()
				let data = JSON.parse(res.data)
				resolve(data.result)
			}
		});
	});
}

const uploadMediaSuccess = (data) => {
	momentMediaList.value.push({url:data.result})
}

const removeImage = (index) => {
	momentMediaList.value.splice(index, 1)
	if(momentMediaList.value.length == 0){
		momentInfo.value.mediaType = null
	}
}

const removeVideo = () => {
	videoUrl.value = ''
	videoCover.value = '' // 清空封面
	momentInfo.value.mediaType = null
	if(videoContext.value) {
		videoContext.value.pause()
	}
}

const playVideo = () => {
	if(videoContext.value) {
		videoContext.value.play()
		showPlay.value = false
	}
}

const noneContent = () => {
	if(momentInfo.value.content == undefined || momentInfo.value.content == null 
	|| momentInfo.value.content == ''){
		return true
	}
	return false
}

const submit = () => {
	if(noneContent()){
		return
	}
	
	// 根据媒体类型设置mediaList
	if(momentInfo.value.mediaType === 1) {
		momentInfo.value.mediaList = momentMediaList.value.map(item => ({
			url: item.url,
			type: 'image'
		}))
	} else if(momentInfo.value.mediaType === 2) {
		momentInfo.value.mediaList = [{
			url: videoUrl.value +','+ videoCover.value,
			cover: videoCover.value, // 添加封面
			type: 'video'
		}]
	} else {
		momentInfo.value.mediaList = []
	}
	
	request.post("moment/add", momentInfo.value).then(res => {
		uni.$emit('newMomnet', {});
		uni.navigateBack();
	})
}
</script>

<style lang="scss">
.info-wrap{
	border-radius: 50rpx 50rpx 0 0;
	background-color: #FFF;
	.content{
		padding: 40rpx 40rpx;
		height: 250rpx;
		border-radius: 20rpx;
		position: relative;
		font-size: 30rpx;
		textarea::placeholder{
			font-size: 30rpx;
			color:#ccc;
		}
		.txt{
			padding-left: 30rpx;
			padding-top: 30rpx;
		}
	}
	.post-img-wrap {
		padding: 0 20rpx;
		image {
			border-radius: 10rpx;
			margin: 10rpx;
		}
		.slot-btn {
			margin: 10rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 212rpx;
			height: 212rpx;
			border-radius: 10rpx;
			background-color: $lf-bg-grey-week;
		}
		.slot-txt {
			margin-top: 17rpx;
			font-size: 28rpx;
			line-height: 33rpx;
			opacity: 0.5;
		}
	}
	.video-wrap{
		margin: 20rpx 30rpx;
		position: relative;
		width: 690rpx;
		.upload-video{
			width: 100%;
			height: 400rpx;
			border-radius: 10rpx;
		}
		image{
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			height: 100rpx;
			width: 100rpx;
			bottom: 0;
			margin: auto;
			z-index: 10;
		}
		.icon{
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			background-color: $lf-bg-grey;
			border-radius: 50rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 10rpx;
			z-index: 11;
		}
	}
	.footer{
		position: fixed;
		bottom: 50rpx;
		width: 100%;
		padding: 10rpx;
		color: $lf-text-grey;
		.tool2{
			display: flex;
			align-items: center;
			image{
				width: 60rpx;
				height: 60rpx;
			}
			.disabled{
				opacity: 0.5;
			}
			.submit{
				margin-left: auto;
				margin-right: 30rpx;
				border-radius: 40rpx;
				padding: 10rpx 20rpx;
				font-size: 28rpx;
				text-align: center;
				color: $lf-text-white;
			}
			.blue{
				background-color: $lf-bg-blue;
			}
			.grey{
				background-color: $lf-bg-grey;
			}
		}
	}
}
</style>